import org.I0Itec.zkclient.ZkConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ConnectionPool {

    List<Connection> conns = new ArrayList<Connection>();
    int size;

    private static class ConnectionPoolHoler {
        private static ConnectionPool instance = new ConnectionPool(2);
    }


    public static ConnectionPool getInstance() {
        return ConnectionPoolHoler.instance;
    }

    private ConnectionPool(int size) {
        this.size = size;
        init();
    }

    //从zk节点获取配置信息，初始化数据库连接池
    public void init() {
        final GetJdbcConfig getJdbcConfig = GetJdbcConfig.getInstance();
        if (getJdbcConfig.getPath().equals("")) return;
        if (getJdbcConfig.getUrl().equals("")) getJdbcConfig.getFromZk();
        try {
            Class.forName(getJdbcConfig.getDriver());
            for (int i = 0; i < size; i++) {
                Connection c = DriverManager.getConnection(getJdbcConfig.getUrl(), getJdbcConfig.getUser(), getJdbcConfig.getPwd());
                conns.add(c);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("ConnectionPool connects to '"+ getJdbcConfig.getUrl() +"' !");
    }

    //返回连接池中的连接
    public synchronized Connection getConnection() {
        while (conns.isEmpty()) {
            try {
                //连接池为空，则等待连接归还
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Connection c = conns.remove(0);
        return c;
    }

    //归还连接池连接
    public synchronized void returnConnection(Connection c) {
        conns.add(c);
        this.notifyAll();
    }

    //关闭连接池连接，清空连接池
    public void close() {
        for (int i = 0; i < size; i++) {
            try {
                conns.remove(0).close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        System.out.println("ConnectionPool closes on '"+ GetJdbcConfig.getInstance().getUrl() +"' !");
    }

}